package com.clkj.aimin.service.user;

import com.alibaba.fastjson.JSONObject;
import com.clkj.aimin.dao.doctor.DoctorMapper;
import com.clkj.aimin.dao.helper.HelperTalkMapper;
import com.clkj.aimin.dao.user.*;
import com.clkj.aimin.pojo.common.*;
import com.clkj.aimin.pojo.doctor.Ewm;
import com.clkj.aimin.pojo.helper.HelperTalk;
import com.clkj.aimin.pojo.user.*;
import com.clkj.aimin.dao.doctor.ErWeiMaMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.*;

/**
 * @author yawang
 * @create 2024/04/02 16:54:32
 **/
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserHealthMapper userHealthMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserCasesMapper userCasesMapper;

    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private HelperTalkMapper helperTalkMapper;

    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private RechargeMapper rechargeMapper;

    @Autowired
    private ErWeiMaMapper weiMaMapper;

    @Autowired
    private UserOrderImgMapper userOrderImgMapper;

    @Autowired
    private VersionMapper versionMapper;

    private Map map;
    @Override
    public User updateUser(User user,HttpServletRequest request) {
        user.setUserName(user.getUserName());
        user.setUserId(user.getUserId());
        user.setBirth(user.getBirth());
        user.setUserTel(user.getUserTel());
        user.setUserSex(user.getUserSex());
        user.setCardCode(user.getCardCode());
        user.setDoctorId(user.getDoctorId());
        String contentType = request.getContentType();
        if(contentType.contains("multipart/form-data")){
            MultipartFile file = ((MultipartRequest) request).getFile("file");
            String fileName = "";
            if (file != null) {
                fileName = OSSUtil.uploadingImg(file, "doctor/user");
            }
            user.setUserImg(fileName);
        }


        userMapper.updateByPrimaryKeySelective(user);
        return user;
    }

    @Override
    public User getUserByOpenId(String openId) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openId",openId);
        return userMapper.selectOneByExample(example);
    }

    @Override
    public User getUserById(Integer userId) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        return userMapper.selectOneByExample(example);
    }

    @Override
    public void  addHealthRecords(UserHealth health) {
        if(health.getRecordId()!=null){
            userHealthMapper.updateByPrimaryKeySelective(health);
        }else{
            userHealthMapper.insertSelective(health);
        }

    }

    @Override
    public UserHealth getHealthRecord(Integer userId) {
        Example example = new Example(UserHealth.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        return userHealthMapper.selectOneByExample(example);
    }

    @Override
    public void addUserType(Integer userType, Integer num) {
        UserType userTypes = null;
        List<UserType> typeList = new ArrayList<>();
        for (Integer i = 0; i < num; i++) {
            userTypes = new UserType();
            String codes = Util.getRandomIntegerByLength(6);
            userTypes.setTypeCode(codes);
            userTypes.setUserType(userType);
            userTypes.setIsUsed(0);
            typeList.add(userTypes);
        }
        if(num>0){
           userTypeMapper.insertList(typeList);
        }

    }

    @Override
    public List<UserType> listTypes() {
        Example example =  new Example(UserType.class);
        example.orderBy("isUsed").desc();
        return userTypeMapper.selectByExample(example);
    }

    @Override
    public Map login(String unionId,String openId,String userName,String userImg,String userSex) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unionId",unionId);
        User user = userMapper.selectOneByExample(example);
        map = new HashMap();
        if(user==null){
            user = new User();
            user.setUserImg(userImg);
            user.setUserName(userName);
            user.setUnionId(unionId);
            user.setUserType(0);
            user.setUserSex(userSex);
//            user.setDoctorId(doctorId);
            user.setLoveNum(0);
            user.setRegistNum(0);
//            user.setHelperId(helperId);
            user.setIsVip(0);
            user.setOpenId(openId);
            user.setParentId(0);
            user.setTaskScore(0);
            userMapper.addUser(user);
        }else{
            user.setOpenId(openId);
            userMapper.updateByPrimaryKeySelective(user);
        }
        map.put("user",userMapper.getGeren(user.getUserId()));
        user = null;
        example =null;
        criteria = null;
        return map;
    }

    @Override
    public Result updateUserTask(Integer userId, String taskName, Integer score) {
        String key = userId+"task"+"_"+DateFormatHelper.today();
        Object value = redisTemplate.opsForHash().get(key, taskName);
        // 判断是否为 null
        if (value != null) {
            Map<String, Integer> map = new HashMap<>();
            map.put("flag", 0);
            return new Result(false, StatusCode.ERROR, "该活动今日已完成", map);
        }
        //更新用户积分
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        User user = userMapper.selectOneByExample(example);
        user.setTaskScore(user.getTaskScore()+score);
        userMapper.updateByPrimaryKeySelective(user);
        //将今天做过的任务存入缓存
        redisTemplate.opsForHash().put(key,taskName,score);
        Map map = new HashMap();
        map.put("flag", 1);
        //将今天完成的任务保存
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setTaskName(taskName);
        taskInfo.setUserId(userId);
        taskInfo.setCreateTime(DateFormatHelper.currentTimes());
        taskInfo.setScoreNum(score);
        taskInfoMapper.insertSelective(taskInfo);
        return new Result(true, StatusCode.ACCESSERROR, "完成"+taskName+"任务",map);
    }

    @Override
    public void addUserCases(Integer userId, HttpServletRequest request) {
        List<MultipartFile> file1 = ((MultipartRequest) request).getFiles("cases");
//        List<MultipartFile> file2 = ((MultipartRequest) request).getFiles("report");
        String  names="";
        if (file1.size() > 0){
            for (MultipartFile multipartFile : file1) {
                String fileName = OSSUtil.uploadingImg(multipartFile, "doctor/user/image");
                String str[] = fileName.split(",");
                names +=str[str.length-1]+",";

            }
        }
        UserCases userCases = new UserCases();
        userCases.setImageType(0);
        userCases.setImageContent(names);
        userCases.setUserId(userId);
        userCases.setCreateTime(DateFormatHelper.currentTimes());
        userCasesMapper.insertSelective(userCases);
//        if (file2.size() > 0){
//            for (MultipartFile multipartFile : file2) {
//                String fileName = OSSUtil.uploadingImg(multipartFile, "doctor/user/image");
//                UserCases userCases = new UserCases();
//                userCases.setImageType(1);
//                userCases.setImageContent(fileName);
//                userCases.setUserId(userId);
//                userCases.setCreateTime(DateFormatHelper.currentTimes());
//                userCasesMapper.insertSelective(userCases);
//            }
//        }
    }

    @Override
    public List<UserCases> getUserCases(Integer userId, Integer type) {
        Example example = new Example(UserCases.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        if(type==0){
            criteria.andEqualTo("imageType",0);
        }else if(type==1){
            criteria.andEqualTo("imageType",1);
        }
        List<UserCases> userCases = userCasesMapper.selectByExample(example);
//        Map<String, List<UserCases>> resultMap = new HashMap<>();
//        for (UserCases userCase : userCases) {
//            String time = userCase.getCreateTime();
//            if (!resultMap.containsKey(time)) {
//                resultMap.put(time, new ArrayList<>());
//            }
//            resultMap.get(time).add(userCase);
//        }
        return userCases;
    }

    @Override
    public void deleteUserCases(Integer userId, String ids) {
        String[] Ids = ids.split(",");
        Example example = new Example(UserCases.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("imageId",Arrays.asList(Ids));
        userCasesMapper.deleteByExample(example);

    }

    @Override
    public Result addUserByFamilyCode(String familyCode, String userId) {
        //根据邀请码获取主用户信息
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentCode",familyCode).andEqualTo("parentId",0);
        User user = userMapper.selectOneByExample(example);
        if (user==null){
            return new Result(false, StatusCode.ERROR, "当前家庭码无效");
        }
        User user1 = new User();
        user1.setParentId(user.getUserId());
        user1.setParentCode(user.getParentCode());
        user1.setUserId(Integer.parseInt(userId));
        userMapper.updateByPrimaryKeySelective(user1);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    @Override
    public  Map userAddOrder(UserOrder userOrder,HttpServletRequest request) {
        userOrder.setCreateTime(DateFormatHelper.currentTimes());
        String orderNum = new Date().getTime() /1000L+"";
        userOrder.setOrderNumber(orderNum);
        userOrderMapper.insertSelective(userOrder);
        List<MultipartFile> file = ((MultipartRequest) request).getFiles("file");
        if (file.size() > 0){
            UserOrderImg img = null;
            List<UserOrderImg> imgList = new ArrayList<>();
            for (MultipartFile multipartFile : file) {
                String fileName = OSSUtil.uploadingImg(multipartFile, "doctor/user/image");
                img = new UserOrderImg();
                img.setImgUrl(fileName);
                img.setOrderNumber(orderNum);
                imgList.add(img);
            }
            userOrderImgMapper.insertList(imgList);
        }

        User user = userMapper.selectByPrimaryKey(userOrder.getApplyId());
        if(userOrder.getOrderType() == 0 ){
            user.setRegistNum(user.getRegistNum() -1);
        }else{
            user.setLoveNum(user.getLoveNum() -1);
        }

        userMapper.updateByPrimaryKeySelective(user);
        return null;

    }

    @Override
    public Set getUserTask(Integer userId) {
        String key = userId+"task"+"_"+DateFormatHelper.today();
        // 获取哈希中的所有键
        Set<Object> keys = redisTemplate.opsForHash().keys(key);
        if(keys.size()==0){
            redisTemplate.delete(key);
        }
        return keys;
    }

    @Override
    public void addHelperTalk(Integer userId, Integer helpId, String content) {
        Example example = new Example(HelperTalk.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId).andEqualTo("helperId",helpId).andEqualTo("parentId",0);
        HelperTalk helperTalk1 = helperTalkMapper.selectOneByExample(example);
        HelperTalk helperTalk = new HelperTalk();
        helperTalk.setHelperId(helpId);
        helperTalk.setUserId(userId);
        helperTalk.setTalkDetail(content);
        helperTalk.setCreateTime(DateFormatHelper.currentTimes());
        helperTalk.setUserType(0);
        helperTalk.setHelperIsNew(0);
        helperTalk.setUserIsNew(1);
        if (helperTalk1==null){
            helperTalk.setParentId(0);
        }else {
            helperTalk.setParentId(helperTalk1.getTalkId());
        }
        helperTalkMapper.insertSelective(helperTalk);
    }

    @Override
    public List<HelperTalk> getDoctorInfo(Integer userId, Integer helper) {
        Example example = new Example(HelperTalk.class);
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId).andEqualTo("helperId",helper);
        List<HelperTalk> helperTalks = helperTalkMapper.selectByExample(example);
        HelperTalk helperTalk = new HelperTalk();
        helperTalk.setUserIsNew(1);
        helperTalkMapper.updateByExampleSelective(helperTalk,example);
        return helperTalks;
    }

    @Override
    public Integer getUserUnRead(Integer userId) {
        Example example = new Example(HelperTalk.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId).andEqualTo("userIsNew",0);
        return helperTalkMapper.selectCountByExample(example);
    }

    @Override
    public Map addUserOrder(Integer userId, String rechargeMoney,Integer doctorId,Integer helperId,Integer flag,Integer applyId,Integer parentId,HttpServletRequest request) {

        SortedMap<String,Object> packageParams = new TreeMap();

        String orderNum = new Date().getTime() /1000L+"";
        System.out.println(orderNum);
        String redirect_url="https://www.ccclkj.cn:2035/user/paySuccess";
        //处理业务

        UserOrder userOrder = new UserOrder();
        userOrder.setUserId(userId);
        userOrder.setDoctorId(doctorId);
        userOrder.setCreateTime(DateFormatHelper.currentTimes());
        userOrder.setPayType(1);
        userOrder.setOrderType(flag);
        userOrder.setHelperId(helperId);
        userOrder.setParentId(parentId);

        userOrder.setOrderNumber(orderNum);
        userOrder.setOrderTotal(rechargeMoney);
        userOrder.setApplyId(applyId);
        if(applyId==userId){
            userOrder.setOrderStatus(3);
        }else{
            userOrder.setPayStatus(0);
        }
        userOrderMapper.insertSelective(userOrder);
//        List<MultipartFile> file = ((MultipartRequest) request).getFiles("file");
//        if (file.size() > 0){
//            UserOrderImg img = null;
//            List<UserOrderImg> imgList = new ArrayList<>();
//            for (MultipartFile multipartFile : file) {
//                String fileName = OSSUtil.uploadingImg(multipartFile, "doctor/user/image");
//                img = new UserOrderImg();
//                img.setImgUrl(fileName);
//                img.setOrderNumber(orderNum);
//                imgList.add(img);
//            }
//            userOrderImgMapper.insertList(imgList);
//        }





        orderNum = orderNum+"A"+((int) (Math.random() * 90) + 10);

        String appId = ImgApi.appid;
        String attach = userId + "@" +rechargeMoney+"@"+flag;
        String nonceStr = DateFormatHelper.getCurTimestamp().toString();
        String Ip = Util.getIpAddr(request);
        String totalFee = Util.getMoney(rechargeMoney);
        String mchId = ImgApi.partner;
        String body = "开通家庭医生";

        packageParams.put("appid",appId);
        packageParams.put("attach",attach);
        packageParams.put("body",body);
        packageParams.put("mch_id",mchId);
        packageParams.put("nonce_str", nonceStr);
        packageParams.put("notify_url",redirect_url);
        packageParams.put("out_trade_no",orderNum);
        packageParams.put("spbill_create_ip", Ip);
        packageParams.put("total_fee",totalFee);
        packageParams.put("trade_type","APP");
        RequestHandler requestHandler = new RequestHandler(null,null);
        requestHandler.init(ImgApi.appid,ImgApi.appsecret ,ImgApi.partnetKey,ImgApi.partner);
        String sign = requestHandler.createSign(packageParams);
        System.out.println(sign);
        String xml = "<xml>" + "<appid>" + appId + "</appid>" + "<attach>"
                + attach + "</attach>" + "<body><![CDATA[" + body
                + "]]></body>" + "<mch_id>" + mchId + "</mch_id>"
                + "<nonce_str>" + nonceStr + "</nonce_str>" + "<notify_url>"
                + redirect_url + "</notify_url>" + "<out_trade_no>"
                + orderNum + "</out_trade_no>" +
                "<spbill_create_ip>" + Ip + "</spbill_create_ip>"
                + "<sign>" + sign + "</sign>" + "<total_fee>" + totalFee
                + "</total_fee>" + "<trade_type>" + "APP"
                + "</trade_type>" +
                "</xml>";
        System.out.println(xml);
        String prePayId = "";
        String createdOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String result = PayUtil.httpRequest(createdOrderURL,"POST",xml);
        System.out.println(result);
        SortedMap<String,Object> finalpackage = new TreeMap();
        try {
            Map map = PayUtil.doXMLParse(result);
            String str = String.valueOf(System.currentTimeMillis()/1000);
            String returnCode = map.get("return_code").toString();
            if(returnCode.equals("SUCCESS")){
                prePayId = map.get("prepay_id").toString();
                finalpackage.put("appid",appId);
                finalpackage.put("noncestr",nonceStr);
                finalpackage.put("package","Sign=WXPay");
                finalpackage.put("partnerid",mchId);
                finalpackage.put("prepayid",prePayId);
                finalpackage.put("timestamp",str);
                String finalSign = requestHandler.createSign(finalpackage);
                finalpackage.put("sign",finalSign);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map = new HashMap();
        map.put("finalPackage",finalpackage);

        return map;
    }
    @Override
    public void paySuccess(HttpServletRequest request, HttpServletResponse response) {
        System.out.println( "进来了");
        String resXml = "";
        InputStream inStream;
        String order_num="";
        String attach="";
        String transaction_id="";
        try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map m = PayUtil.parseXmlToList2(result);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            if ("SUCCESS".equals(m.get("result_code").toString())) {
                // 更新支付状态
                order_num = m.get("out_trade_no").toString().split("A")[0];
                System.out.println(order_num + "订单号是什么");
                attach = m.get("attach").toString();
                transaction_id = m.get("transaction_id").toString();
                // 获取微信生成的订单号

                resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";

            } else {
                resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";

            }
            out.write(resXml.getBytes());
            out.flush();
            out.close();

            deal(attach,transaction_id,order_num);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void deal(String attach,String transaction_id,String order_num){


        Example example = new Example(UserOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderNumber",order_num);
        UserOrder userOrder = new UserOrder();
        userOrder.setPayStatus(1);
        userOrder.setOrderStatus(3);
        userOrder.setTransactionId(transaction_id);
        userOrderMapper.updateByExampleSelective(userOrder,example);
        String[] str = attach.split("@");
        //0加号 1亲情就诊 2 开通家庭套餐
//                userId + "@" +rechargeMoney+"@"+flag;
        User user = userMapper.selectByPrimaryKey(Integer.parseInt(str[0]));
        if(Integer.parseInt(str[2])==2){
            user.setIsVip(1);
            user.setRegistNum(user.getRegistNum() +1);
            user.setLoveNum(user.getLoveNum() + 1);
            try {
                String newDate=null;
                if(user.getVipTime()!=null){
                    newDate = DateFormatHelper.getAddDay(user.getVipTime(),"year",365,"yyyy-MM-dd HH:mm:ss" );

                }else{
                    newDate = DateFormatHelper.getAddDay("year",365);
                }
                user.setVipTime(newDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else if(Integer.parseInt(str[2])==0){
            user.setRegistNum(user.getRegistNum() +1);
        }else if(Integer.parseInt(str[2])==1){
            user.setLoveNum(user.getLoveNum() +1);
        }

        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Map telLogin(String tel, String password) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userTel",tel).andEqualTo("password",password);
        User user = userMapper.selectOneByExample(example);
        map = new HashMap();
        if(user==null){
            map.put("flag","error");
            map.put("msg","用户不存在");
            return map;
        }
        else{
            map.put("flag","success");
            map.put("user",userMapper.getGeren(user.getUserId()));
            return map;
        }
    }

    @Override
    public String creatCode(Integer userId) {
        String code = Util.getRandomIntegerByLength(6);
        User user = new User();
        user.setParentCode(code);
        user.setUserId(userId);
        user.setParentId(0);
        userMapper.updateByPrimaryKeySelective(user);

        return code;
    }



    @Override
    public List<UserOrder> getUserOrderDetail(Integer userId,String parentCode) {
        //获取该用户的所有家庭成员
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        List<UserOrder> orders= null;
        if(parentCode!=null){
            criteria.andEqualTo("parentCode",parentCode).andEqualTo("parentId",0);
            User user = userMapper.selectOneByExample(example);
            orders = userOrderMapper.getUserOrderDetail(user.getUserId());
        }else{
            orders = userOrderMapper.getUserOrderDetail(userId);
        }

        List<UserOrderImg> imgList= null;
        for (UserOrder order : orders) {
            if(order.getOrderType()==1){
                 example = new Example(UserOrderImg.class);
                criteria = example.createCriteria();
                criteria.andEqualTo("orderNumber",order.getOrderNumber());

                //亲情就诊
                imgList =userOrderImgMapper.selectByExample(example);
                order.setImgList(imgList);

            }
        }
        return orders;
    }

    @Override
    public Map getUserInfoById(Integer userId) {
        //获取个人基本信息
        User userinfo = userMapper.getGeren(userId);
        //获取该用户的所有家庭成员
        List<User> users= null;
        if(userinfo.getParentCode()!=null){
            users = userMapper.listFamilyUsers(userinfo.getParentCode());
        }
        Map map = new HashMap();
        map.put("userinfo",userinfo);
        map.put("familyList",users);
        return map;
    }

    @Override
    public List<TaskInfo> getUserTaskInfo(Integer userId) {
        Example example = new Example(TaskInfo.class);
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        return taskInfoMapper.selectByExample(example);
    }

    public void payTest(Integer userId, String rechargeMoney,Integer doctorId,Integer helperId,Integer flag,Integer applyId,Integer parentId,
                        HttpServletRequest request){


        UserOrder userOrder = new UserOrder();
        userOrder.setUserId(userId);
        userOrder.setDoctorId(doctorId);
        userOrder.setCreateTime(DateFormatHelper.currentTimes());
        userOrder.setPayType(1);
        userOrder.setOrderType(flag);
        userOrder.setHelperId(helperId);
        userOrder.setParentId(parentId);
        userOrder.setPayStatus(0);
        userOrder.setApplyId(applyId);
        userOrder.setOrderNumber(new Date().getTime() /1000L+"");
        userOrder.setOrderTotal(rechargeMoney);
        if(applyId==userId){
            userOrder.setOrderStatus(3);
        }else{
            userOrder.setPayStatus(0);
        }
        userOrderMapper.insertSelective(userOrder);
        List<MultipartFile> file = ((MultipartRequest) request).getFiles("file");
        if (file.size() > 0){
            UserOrderImg img = null;
            List<UserOrderImg> imgList = new ArrayList<>();
            for (MultipartFile multipartFile : file) {
                String fileName = OSSUtil.uploadingImg(multipartFile, "doctor/user/image");
                img = new UserOrderImg();
                img.setImgUrl(fileName);
                img.setOrderNumber(userOrder.getOrderNumber());
                imgList.add(img);
            }
            userOrderImgMapper.insertList(imgList);
        }



        //0加号 1亲情就诊 2 开通家庭套餐
//                userId + "@" +rechargeMoney+"@"+flag;
        User user = userMapper.selectByPrimaryKey(userId);
        if(flag==2){
            user.setIsVip(1);
            user.setRegistNum(user.getRegistNum() +1);
            user.setLoveNum(user.getLoveNum() + 1);
            try {
                String newDate=null;
                if(user.getVipTime()!=null){
                    newDate = DateFormatHelper.getAddDay(user.getVipTime(),"year",1,"yyyy-MM-dd HH:mm:ss" );

                }else{
                    newDate = DateFormatHelper.getAddDay("year",1);
                }
                user.setVipTime(newDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else if(flag==0){
            user.setRegistNum(user.getRegistNum() +1);
        }else if(flag==1){
            user.setLoveNum(user.getLoveNum() +1);
        }

        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<User> listFamilyNum(Integer userId, String parentCode) {
        List<User> users = null;
        if(parentCode == null){
            User user = userMapper.selectByPrimaryKey(userId);
            users.add(user);
        }else{
            Example example = new Example(User.class);
            Example.Criteria criteria =  example.createCriteria();
            criteria.andEqualTo("parentCode",parentCode);
            Example.Criteria criteria1 = example.createCriteria();
            criteria1.orGreaterThan("registNum",0).orGreaterThan("loveNum",0);
            example.and(criteria1);
            users = userMapper.selectByExample(example);
        }
        return users;
    }

    @Override
    public List<UserOrder> listApplyList(Integer userId) {
        List<UserOrder> userOrders =  userOrderMapper.listMyApply(userId);
        List<UserOrderImg> imgList= null;
        for (UserOrder order : userOrders) {
            if(order.getOrderType()==1){
                Example example = new Example(UserOrderImg.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("orderNumber",order.getOrderNumber());

                //亲情就诊
                imgList =userOrderImgMapper.selectByExample(example);
                order.setImgList(imgList);

            }
        }
        return userOrders;
    }

    @Override
    @Transactional(rollbackFor =Exception.class )
    public void applyOrder(Integer orderId,Integer status,String note) {
        UserOrder order = userOrderMapper.selectByPrimaryKey(orderId);
        order.setOrderId(orderId);
        if(status==0){
            //审核人不通过
            order.setOrderStatus(4);
            order.setUnPass(note);
            //把号给人退回去
            userMapper.returnNum(order.getApplyId(),order.getOrderType());
        }else{
            order.setOrderStatus(3);
        }
        userOrderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public User geren(Integer userId) {

        return userMapper.getGeren(userId);
    }

    @Override
    public String erweima(Integer doctorId, Integer helperId) {
        Example example = new Example(Ewm.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("doctorId",doctorId).andEqualTo("helperId",helperId);
        Ewm ewm =weiMaMapper.selectOneByExample(example);
        if(ewm==null){
            //生成二维码
//            String path = "https://aimin-imgs.oss-cn-beijing.aliyuncs.com/doctor/er/";
            String path = "D:\\nginx-1.19.1\\html\\zhibanzhang\\resource\\aimin\\doctor\\er";
            String url = "https://www.ccclkj.cn/sharePage/aimin.html?doctorId=" +doctorId+"&helperId="+helperId;
             Util.creatPic(url, doctorId+"", path, null);
            ewm = new Ewm();
            ewm.setDoctorId(doctorId);
            ewm.setHelperId(helperId);
            ewm.setErImg(doctorId+".png");
            weiMaMapper.insertSelective(ewm);

        }
        return ewm.getErImg();
    }

    @Override
    public void scanMa(String code,Integer doctorId,Integer helperId) {
        map = new HashMap();
        String access_token = "";
        String unionid = "";
        String urls = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + ImgApi.wxAppid
                + "&secret="
                + ImgApi.wxAppsecret
                + "&code="
                + code
                + "&grant_type=authorization_code";
        JSONObject json = Util.getResult(urls);
        access_token = json.getString("access_token");
        unionid = json.getString("unionid");
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unionId",unionid);
        User user = userMapper.selectOneByExample(example);
          if(user == null) {
               user = new User();
              user.setUnionId(unionid);
              user.setUserType(0);
                user.setDoctorId(doctorId);
              user.setLoveNum(0);
              user.setRegistNum(0);
                user.setHelperId(helperId);
              user.setIsVip(0);
              user.setParentId(0);
              user.setTaskScore(0);
              userMapper.addUser(user);
            }
    }

    @Override
    public PageInfo listUser(Integer page, Integer size, String userName, Integer doctorId, Integer helperId, Integer userType) {
        PageHelper.startPage(page,size);
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if(userName.length()!=0&&userName!=null){
            criteria.andCondition(" user_name like '%"+userName+"%'");
        }
        if(doctorId!=0){
            criteria.andEqualTo("doctorId",doctorId);
        }
        if(helperId!=0){
            criteria.andEqualTo("helperId",helperId);
        }
        if(userType!=-1){
            criteria.andEqualTo("userType",userType);
        }
        example.orderBy("userId").desc();


        return new PageInfo(userMapper.selectByExample(example));
    }

    @Override
    public void deleteHealth(Integer id) {
        userCasesMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void unApplyService(Integer orderId,String orderNumber, HttpServletRequest request) {
        UserOrder userOrder = new UserOrder();
        userOrder.setOrderId(orderId);
        userOrder.setUnPass(null);
        userOrder.setOrderStatus(3);
        userOrderMapper.updateByPrimaryKeySelective(userOrder);

        List<MultipartFile> file = ((MultipartRequest) request).getFiles("file");
        if (file.size() > 0){
            UserOrderImg img = null;
            List<UserOrderImg> imgList = new ArrayList<>();
            for (MultipartFile multipartFile : file) {
                String fileName = OSSUtil.uploadingImg(multipartFile, "doctor/user/image");
                img = new UserOrderImg();
                img.setImgUrl(fileName);
                img.setOrderNumber(orderNumber);
                imgList.add(img);
            }
            userOrderImgMapper.insertList(imgList);
        }


    }

    @Override
    public List<UserOrder> listMyApply(Integer userId) {
        List<UserOrder> userOrders =  userOrderMapper.listMyApplyList(userId);
        List<UserOrderImg> imgList= null;
        for (UserOrder order : userOrders) {
            if(order.getOrderType()==1){
                Example example = new Example(UserOrderImg.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("orderNumber",order.getOrderNumber());

                //亲情就诊
                imgList =userOrderImgMapper.selectByExample(example);
                order.setImgList(imgList);

            }
        }
        return userOrders;
    }

    @Override
    public List<Version> listNewVer() {
        return versionMapper.listNewVer();
    }

    @Override
    public List<Version> listVer() {
        return versionMapper.listVer();
    }

    @Override
    public void addVer(Version version) {
        versionMapper.insertSelective(version);
    }


}
